#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <assert.h>

using namespace std;
// 测试匿名管道
int main()
{
    // 1.创建匿名管道
    int pipefd[2] = {0};
    int fd = pipe(pipefd);
    assert(fd != -1);

    // 2.创建子进程
    pid_t id = fork();
    assert(id != -1);
    (void)id;

    // 3.测试匿名管道
    if (id == 0)
    {
        // 子进程
        // 子进程关闭写端
        close(pipefd[1]);

        while (true)
        {
            // sleep(5);
            char inbuffer[1024];
            int len = read(pipefd[0], inbuffer, sizeof(inbuffer) - 1);
            if (len > 0)
            {
                cout << inbuffer;
            }
            else if (len == 0)//读端关闭了
            {
                cout << "child quit" << endl;
                break;
            }
        }
        close(pipefd[0]);
        exit(0);
    }
    // 父进程
    // 父进程关闭读端
    close(pipefd[0]);
    int cnt = 0;
    while (true)
    {
        string str = "I am father\n";
        write(pipefd[1], str.c_str(), str.size());
        // sleep(2);
        cout << cnt++ << endl;
        break;
    }
    cout << "father write close" << endl;
    close(pipefd[1]);

    waitpid(id, nullptr, 0);

    return 0;
}